package net.mingsoft.document.action.web;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.*;
import net.mingsoft.base.entity.ResultData;
import net.mingsoft.basic.action.BaseAction;
import net.mingsoft.basic.util.SqlUtil;
import net.mingsoft.document.action.q.*;
import net.mingsoft.document.action.r.*;
import net.mingsoft.document.biz.FileBiz;
import net.mingsoft.document.entity.FileLogEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author gengfa
 * @date 22/01/13
 */
@Api(value = "文件接口", tags = {"内容管理-文档（文件）管理"})
@Controller("WebCmsDocumentAction")
@RequestMapping("/${ms.manager.path}/cms/document")
public class FileAction extends BaseAction {

    @Resource
    FileBiz fileBiz;

    @GetMapping("/index")
    public String index(HttpServletResponse response,HttpServletRequest request){
        return "/cms/document/index";
    }

    @ApiOperation(value = "搜索文件")
    @PostMapping(value = "/search", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses(value = {
            @ApiResponse(code = 0, message = "success", response = FileSearchResponse.class)
    })
    @ResponseBody
    public ResultData search(@RequestBody FileSearchQuery q) {
        if (StringUtils.isNotBlank(q.getFileName())) {
            q.setFileName(SqlUtil.likeStr(q.getFileName()));
        }
        Page<FileSearchResponse> page = fileBiz.searchFile(q);
        return ResultData.build().success(page);
    }

    @ApiOperation(value = "文档/文件列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileName",        value = "文件名"),
            @ApiImplicitParam(name = "createdUserName", value = "创建人"),
            @ApiImplicitParam(name = "pageNo",          value = "页号"),
            @ApiImplicitParam(name = "pageSize",        value = "分页大小")
    })
    @PostMapping(value = "/list", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResultData list(@RequestBody FileQuery q, HttpServletResponse response, HttpServletRequest request,
                           ModelMap model, BindingResult result) {
        Page<FileEntityResponse> page = fileBiz.list(q);
        return ResultData.build().success(page);
    }

    @ApiOperation(value = "文件日志：传入文件ID即可")
    @PostMapping(value = "/logs", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponse(code = 0, message = "success", response = FileLogEntity.class)
    @ResponseBody
    public ResultData logs(@RequestBody FileLogQuery q) {
        Page<FileLogEntity> page = fileBiz.fileLog(q);
        return ResultData.build().success(page);
    }

    @ApiOperation(value = "目录树")
    @GetMapping(value = "/dir/tree")
    @ResponseBody
    public ResultData dirTree() {
        return ResultData.build().success(fileBiz.dirTree());
    }

    @ApiOperation(value = "目录列表")
    @PostMapping(value = "/dir/list", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ResponseBody
    public ResultData dirList(@RequestBody DirListQuery query) {
        return ResultData.build().success(fileBiz.dirList(query));
    }

    @ApiOperation(value = "文件列表()")
    @PostMapping(value = "/file/list", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResultData fileTree(@RequestBody FileTreeQuery query) {
        return ResultData.build().success(fileBiz.fileTree(query));
    }

    @ApiOperation(value = "文档/文件上传")
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ResponseBody
    public ResultData upload(UploadFileQuery query) {
        return fileBiz.uploadMultiFiles(query);
    }

    @ApiOperation(value = "创建文件夹")
    @PostMapping(value = "/mkdir", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResultData mkdir(@RequestBody DirQuery query) {
        //if (query.validate()) {
            MakeDirectoryResponse response = fileBiz.mkdir(query);
            if (response.getId() != null) {
                return ResultData.build().success(response);
            }
        //}
        return ResultData.build().error("unsafe params or file\\dir exists");
    }

    @ApiOperation(value = "删除文件")
    @PostMapping(value = "/delete", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResultData delete(@RequestBody List<String> fileIds) {
        if (fileBiz.delete(fileIds)) {
            return ResultData.build().success();
        }
        return ResultData.build().error();
    }

    @ApiOperation(value = "修改编号/名称")
    @PostMapping(value = "/modify", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "success", response = ModifyResponse.class)
    })
    public ResultData modify(@RequestBody FileModifyQuery query) {
        if (query.validate()) {
            ModifyResponse modify = fileBiz.modify(query);
            if (modify.isModified()) {
                return ResultData.build().success(modify);
            }
            return ResultData.build().error(modify.getFailedType());
        }
        return ResultData.build().error();
    }

    @ApiOperation(value = "分享")
    @PostMapping(value = "/share", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResultData share(@RequestBody FileShareQuery query) {
        if (query.validate()) {
            ShareResponse response = fileBiz.share(query);
            return ResultData.build().success(response);
    }
        return ResultData.build().error("请正确配置'有效期'");
    }

    @ApiOperation(value = "下载")
    @PostMapping(value = "/download", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public void download(@RequestBody FileDownloadQuery query, HttpServletResponse response) {
        if (query.validate()) {
            fileBiz.download(query, response);
        }
    }

    @ApiOperation(value = "预览")
    @GetMapping(value = "/preview")
    @ResponseBody
    public void preview(@RequestParam("id") String fileId, HttpServletResponse response) {
        if (StringUtils.isNotBlank(fileId)) {
            fileBiz.download(new FileDownloadQuery().setId(fileId), response);
        }
    }

    @ApiOperation(value = "授权")
    @PostMapping(value = "/grant", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResultData grant(@RequestBody FileGrantQuery query) {
        if (fileBiz.grant(query)) {
            return ResultData.build().success();
        }
        return ResultData.build().error();
    }

    @ApiOperation(value = "权限列表")
    @GetMapping(value = "/permission/{fileId}")
    @ApiResponse(code = 0, message = "success", response = PermissionWrRdResponse.class)
    @ResponseBody
    public ResultData permission(@PathVariable String fileId) {
        return ResultData.build().success(fileBiz.permission(fileId));
    }

    @ApiOperation(value = "收藏")
    @PostMapping(value = "/star", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResultData star(@RequestBody FileStarQuery query) {
        if (fileBiz.star(query)) {
            return ResultData.build().success();
        }
        return ResultData.build().error();
    }

    @ApiOperation(value = "移动/复制：操作类型 移动：MV. 复制：CP")
    @PostMapping(value = "/mvcp", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResultData moveCopy(@RequestBody FileMoveAndCopyQuery query) {
        MoveCopyResponse response = fileBiz.moveCopy(query);
        if (response.isOp()) {
            return ResultData.build().success(response);
        }
        return ResultData.build().error();
    }
}
